package covertjava.intercept;

/**
 * <p>Custom security manager that intercepts System.exit()</p>
 * <p>Copyright: Copyright (c) 2004 Sams Publishing</p>
 * @author Alex Kalinovsky
 * @version 1.0
 */
public class InterceptingSecurityManager extends SecurityManager {

    protected boolean exitAllowed = false;

    public InterceptingSecurityManager() {
    }

    public boolean isExitAllowed() {
        return this.exitAllowed;
    }

    public void setExitAllowed(boolean exitAllowed) {
        this.exitAllowed = exitAllowed;
    }

    public void checkExit(int status) {
        if(this.exitAllowed == false) {
            throw new SecurityException("Exit not allwoed");
        }
    }


    public static void main(String[] args) {
        InterceptingSecurityManager secManager = new InterceptingSecurityManager();
        System.setSecurityManager(secManager);
        try {
            System.out.println("Run some logic...");
            System.exit(1);
        }
        catch (Throwable x) {
            if (x instanceof SecurityException)
                System.out.println("Intercepted System.exit()");
            else
                x.printStackTrace();
        }
        System.out.println("Run more logic...");
        secManager.setExitAllowed(true);
        System.out.println("Finished");
    }


}
